//    Copyright (C) Kherty.  All rights reserved.
using System.Diagnostics.Contracts;
using OpenLS.Spreadsheet.Expressions;

namespace OpenLS.Spreadsheet.Formats.Biff
{
    internal struct CellReferenceAddress
    {
        private readonly bool _absoluteColumn;
        private readonly bool _absoluteRow;
        private readonly int _column;

        private readonly int _row;
        public override string ToString()
        {
            return (((char)('A' + _column))).ToString() + (_row + 1);
        }

        public CellReferenceAddress(CellReference cellReference): this(cellReference.Row.Anchor.Index, cellReference.Column.Anchor.Index, 
            cellReference.Row.IsLocked, cellReference.Column.IsLocked)
        {
            
        }

        public CellReferenceAddress(int row, int column, bool absoluteRow, bool absoluteColumn)
        {
            Contract.Requires( column >= 0);
            Contract.Requires(row >= 0);
            _column = column;
            _row = row;
            _absoluteColumn = absoluteColumn;
            _absoluteRow = absoluteRow;
        }

        public int Column
        {
            get { return _column; }
        }

        public int Row
        {
            get { return _row; }
        }

        public bool AbsoluteRow
        {
            get { return _absoluteRow; }
        }

        public bool AbsoluteColumn
        {
            get { return _absoluteColumn; }
        }


        internal CellReference ToReference(Worksheet ws)
        {
            return new StaticCellReference(
                new AnchoredRowReference(ws.Rows[Row], AbsoluteRow),
                new AnchoredColumnReference(ws.Columns[Column], AbsoluteColumn));
        }

        internal CellReference ToReferenceRelative(Cell cell)
        {
            Contract.Requires(cell != null);
            Worksheet ws = cell.Worksheet;
            return new StaticCellReference(
                new AnchoredRowReference(AbsoluteRow ? ws.Rows[Row] : ws.Rows[cell.Row.Index + Row], AbsoluteRow),
                new AnchoredColumnReference(
                    AbsoluteColumn ? ws.Columns[Column] : ws.Columns[cell.Column.Index + Column], AbsoluteColumn));
        }
    }
}